package com.ruoyi.flowable.listener;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.equ.domain.vo.SignAndStampVo;
import com.ruoyi.equ.service.IEquRepairService;
import com.ruoyi.framework.config.ServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 签名执行监听器
 */
@Slf4j
@Component("signExecutionListener")
public class SignExecutionListener implements ExecutionListener {
    private static final IEquRepairService repairService = SpringUtils.getBean(IEquRepairService.class);

    @Override
    public void notify(DelegateExecution execution) {
        if ("start".equals(execution.getEventName())) {
            String activityId = execution.getCurrentActivityId();
            // 获取原始URL数据
            SignAndStampVo signAndStamp = repairService.getSignAndStamp();
            String signatureUrl = signAndStamp.getSignature();
            String leaderSignUrl =  signAndStamp.getleaderSign();
            String stampUrl = signAndStamp.getStamp();
            // 转换为目标格式并设置
            setFormattedVariable(execution, "signature_" + activityId, signatureUrl, "负责人签字");
            setFormattedVariable(execution, "leaderSign_" + activityId, leaderSignUrl, "部门负责人签名");
            setFormattedVariable(execution, "stamp_" + activityId, stampUrl, "电子盖章");
        }
    }

    // 转换为目标格式并设置
    private void setFormattedVariable(DelegateExecution execution, String varName, String fileUrl, String desc) {
        if (StringUtils.isNotBlank(fileUrl)) {
            List<Map<String, Object>> fileList = new ArrayList<>();
            Map<String, Object> fileObj = new HashMap<>();
            fileObj.put("url", fileUrl);
            fileObj.put("name", extractFileName(fileUrl, desc));
            fileObj.put("uid", "uid_" + varName + "_" + System.currentTimeMillis());
            fileObj.put("status", "success");
            fileList.add(fileObj);
            execution.setVariable(varName, fileList);
        }
    }

    /**
     * 从URL中提取文件名，使用desc作为前缀，URL中的后缀作为文件后缀
     */
    private String extractFileName(String url, String desc) {
        if (StringUtils.isBlank(url)) {
            return desc + ".jpg"; // 默认后缀
        }
        try {
            // URL解码
            String decodedUrl = URLDecoder.decode(url, StandardCharsets.UTF_8.name());
            // 获取URL中的文件名部分（去除查询参数）
            String fileNamePart = decodedUrl;
            if (decodedUrl.contains("?")) {
                fileNamePart = decodedUrl.substring(0, decodedUrl.indexOf("?"));
            }
            // 提取后缀名（最后一个.之后的内容）
            String fileExtension = extractFileExtension(fileNamePart);
            // 生成时间戳，避免文件名重复
            String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            // 组合文件名：desc + 时间戳 + 后缀
            return desc + "_" + timestamp + fileExtension;

        } catch (Exception e) {
            log.warn("从URL提取文件名失败: {}, 使用默认文件名", url, e);
            return desc + "_" + System.currentTimeMillis() + ".jpg";
        }
    }

    /**
     * 提取文件后缀名
     */
    private String extractFileExtension(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return ".jpg";
        }
        // 找到最后一个点号的位置
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) {
            // 返回包含点号的后缀名，如 ".jpg", ".png", ".jpeg"
            return fileName.substring(lastDotIndex);
        }
        // 如果没有找到合适的后缀名，使用默认的.jpg
        return ".jpg";
    }
}
